<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class VerifyLogin extends CI_Controller {
	function __construct()
	{
		parent::__construct();
		$this -> load -> model('login_model','',TRUE);
	}

	function index()
	{
		//This method will have the credentials validation
		$this->load->library('form_validation');

		$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');

		if($this->form_validation->run() == FALSE)
		{
			//Field validation failed. User redirected to login page
			$this -> load -> helper(array('form'));
			$session_data = $this -> session -> userdata('logged_in');
			$data['username'] = $session_data['username'];
			$data['kode_privilege'] = $session_data['kode_privilege'];
			$data['contents'] = $this -> load -> view('login_view','',true);
			$data['page_title'] = 'Login';
			$this -> load -> view('template_default',$data);
		}
		else
		{
			//Go to private area
			$data['url'] = base_url();
			$data['message'] = 'Loading...';
			$this -> load -> view('loading_view', $data);
		}
	}

	function check_database($password)
	{
		//Field validation succeeded.&nbsp; Validate against database
		$username = $this -> input -> post('username');

		//query the database
		$result = $this -> login_model -> login($username, $password);

		if($result)
		{
			foreach($result as $row)
			{
				$temp_kode_privilege = $row -> kode_privilege;
				$temp_kode_info_cabang = $row -> kode_info_cabang;
			}
			$temp_cabang = $this -> login_model -> cabang($temp_kode_privilege, $temp_kode_info_cabang);
			$cabang = array();
			if($temp_cabang != null) {
				foreach($temp_cabang as $row)
				{
					$cabang[] = array(
						'kode_cabang' => $row -> kode_cabang,
						'nama_cabang' => $row -> nama_cabang,
						'database_cabang' => $row -> database_cabang,
						'kode_harga' => $row -> kode_harga
					);
				}
			}
			$sess_array = array();
			foreach($result as $row)
			{
				$sess_array = array(
					'logged_in' => TRUE,
					'username' => $row -> username,
					'kode_privilege' => $row -> kode_privilege,
					'kode_info_cabang' => $row -> kode_info_cabang,
					'kode_member' => $row -> kode_member,
					'kode_unit' => $row -> kode_unit,
					'kode_upline' => $row -> kode_upline,
					'active' => $row -> active,
					'cabang' => $cabang
				);
				$this -> db -> cache_delete();
				$this -> session -> unset_userdata('logged_in');
				$this -> session -> set_userdata('logged_in', $sess_array);
			}
			return TRUE;
		}
		else
		{
			$this -> form_validation -> set_message('check_database', 'Invalid username or password');
			return false;
		}
	}
}
?>